/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.txt.access.capability.wizard.util;

import it.txt.access.capability.spi.ICapabilityPlugin;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ServiceLoader;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author seccia
 */
public class PluginsLoader {

    public static ArrayList<ICapabilityPlugin> PLUGIN_LIST = new ArrayList<ICapabilityPlugin>();

    private static final Logger LOGGER = Logger.getLogger(PluginsLoader.class.getName());

    public static void loadAdvailablePlugins(File directory) {

        File[] files = directory.listFiles();

        ArrayList<URL> urls = new ArrayList<URL>();

        for (File file : files) {
            if (!file.isDirectory() && file.getName().endsWith(".jar")) {
                try {
                   urls.add(file.toURI().toURL());
                } catch (IOException ex) {
                    LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
                }
            }
        }

        URLClassLoader loader = URLClassLoader.newInstance(
                urls.toArray(new URL[urls.size()]));

        LOGGER.log(Level.INFO, "Number of JAR fouded: {0}", loader.getURLs().length);

        ServiceLoader<ICapabilityPlugin> serviceLoader =
                ServiceLoader.load(ICapabilityPlugin.class, loader);

        Iterator<ICapabilityPlugin> iterator = serviceLoader.iterator();

        while (iterator.hasNext()) {
            ICapabilityPlugin iCapabilityPlugin = iterator.next();
            LOGGER.log(Level.INFO, "Found Plugin: {0}",
                    iCapabilityPlugin.getPluginName());
            PLUGIN_LIST.add(iCapabilityPlugin);
        }
        if(PLUGIN_LIST.isEmpty()){
            LOGGER.log(Level.SEVERE, "No HelloProvider registered");
        }
    }
}
